package com.example.xncs;

import android.content.Context;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 图片数据文件管理器，使用文件存储大量base64数据
 */
public class ImageDataFileManager {
    private static final String TAG = "ImageDataFileManager";
    private static final String DATA_DIR = "image_data";
    private static final String BASE64_FILE = "base64_data.txt";
    private static final String NAMES_FILE = "image_names.txt";
    private static final String INFO_FILE = "data_info.txt";
    private static final String JSON_FILE = "image_data.json";
    
    private Context context;
    private File dataDir;
    
    public ImageDataFileManager(Context context) {
        this.context = context;
        this.dataDir = new File(context.getFilesDir(), DATA_DIR);
        if (!dataDir.exists()) {
            dataDir.mkdirs();
        }
    }
    
    /**
     * 保存base64图片数据列表到文件（使用JSON格式，更安全）
     */
    public void saveBase64ImageList(List<String> base64List, List<String> imageNames) {
        // 首先尝试使用JSON格式保存
        if (saveAsJson(base64List, imageNames)) {
            Log.d(TAG, "使用JSON格式保存成功");
            return;
        }
        
        // 如果JSON保存失败，回退到文本格式
        Log.w(TAG, "JSON保存失败，回退到文本格式");
        saveAsText(base64List, imageNames);
    }
    
    /**
     * 使用JSON格式保存数据（流式写入，避免内存问题）
     */
    private boolean saveAsJson(List<String> base64List, List<String> imageNames) {
        try {
            Log.d(TAG, "开始使用JSON格式保存数据 - base64List大小: " + base64List.size() + ", imageNames大小: " + imageNames.size());
            
            // 验证数据大小
            if (base64List.size() > 10000) {
                Log.w(TAG, "警告：base64列表大小异常: " + base64List.size());
            }
            
            // 检查总数据大小，如果太大则使用文本格式
            long totalSize = 0;
            for (String base64Data : base64List) {
                if (base64Data != null) {
                    totalSize += base64Data.length();
                }
            }
            
            // 如果总大小超过50MB，使用文本格式保存
            if (totalSize > 50 * 1024 * 1024) {
                Log.w(TAG, "数据太大(" + (totalSize / 1024 / 1024) + "MB)，使用文本格式保存");
                return false; // 回退到文本格式
            }
            
            // 使用流式写入JSON，避免内存问题
            File jsonFile = new File(dataDir, JSON_FILE);
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(jsonFile))) {
                writer.write("{\n");
                writer.write("  \"timestamp\": " + System.currentTimeMillis() + ",\n");
                writer.write("  \"count\": " + base64List.size() + ",\n");
                writer.write("  \"base64List\": [\n");
                
                // 写入base64数据
                for (int i = 0; i < base64List.size(); i++) {
                    String base64Data = base64List.get(i);
                    if (base64Data != null && base64Data.length() > 1000000) { // 1MB限制
                        Log.w(TAG, "警告：base64数据过大，位置: " + i + ", 长度: " + base64Data.length());
                        base64Data = base64Data.substring(0, 1000000); // 截断
                    }
                    
                    // 转义JSON特殊字符
                    String escapedData = escapeJsonString(base64Data != null ? base64Data : "");
                    writer.write("    \"" + escapedData + "\"");
                    
                    if (i < base64List.size() - 1) {
                        writer.write(",");
                    }
                    writer.write("\n");
                }
                
                writer.write("  ],\n");
                writer.write("  \"imageNames\": [\n");
                
                // 写入图片名称
                for (int i = 0; i < imageNames.size(); i++) {
                    String name = imageNames.get(i);
                    String escapedName = escapeJsonString(name != null ? name : "未知图片");
                    writer.write("    \"" + escapedName + "\"");
                    
                    if (i < imageNames.size() - 1) {
                        writer.write(",");
                    }
                    writer.write("\n");
                }
                
                writer.write("  ]\n");
                writer.write("}\n");
            }
            
            Log.d(TAG, "JSON格式保存成功，文件大小: " + jsonFile.length() + " bytes");
            return true;
            
        } catch (Exception e) {
            Log.e(TAG, "JSON格式保存失败", e);
            return false;
        }
    }
    
    /**
     * 转义JSON字符串中的特殊字符
     */
    private String escapeJsonString(String str) {
        if (str == null) return "";
        return str.replace("\\", "\\\\")
                 .replace("\"", "\\\"")
                 .replace("\n", "\\n")
                 .replace("\r", "\\r")
                 .replace("\t", "\\t");
    }
    
    /**
     * 使用文本格式保存数据（备用方案，优化内存使用）
     */
    private void saveAsText(List<String> base64List, List<String> imageNames) {
        try {
            Log.d(TAG, "开始使用文本格式保存数据 - base64List大小: " + base64List.size() + ", imageNames大小: " + imageNames.size());
            
            // 保存base64数据
            File base64File = new File(dataDir, BASE64_FILE);
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(base64File), 8192)) { // 8KB缓冲区
                for (int i = 0; i < base64List.size(); i++) {
                    String base64Data = base64List.get(i);
                    if (base64Data != null && !base64Data.isEmpty()) {
                        // 如果单个base64数据太大，截断
                        if (base64Data.length() > 5 * 1024 * 1024) { // 5MB限制
                            Log.w(TAG, "base64数据过大，截断: " + i + ", 原长度: " + base64Data.length());
                            base64Data = base64Data.substring(0, 5 * 1024 * 1024);
                        }
                        
                        writer.write(base64Data);
                        writer.newLine();
                        
                        // 每处理100个数据后刷新缓冲区
                        if (i % 100 == 0) {
                            writer.flush();
                        }
                    } else {
                        writer.write(""); // 空行表示没有数据
                        writer.newLine();
                    }
                }
                writer.flush(); // 确保所有数据写入
            }
            
            // 保存图片名称
            File namesFile = new File(dataDir, NAMES_FILE);
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(namesFile))) {
                for (String name : imageNames) {
                    writer.write(name != null ? name : "未知图片");
                    writer.newLine();
                }
            }
            
            // 保存数据信息
            File infoFile = new File(dataDir, INFO_FILE);
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(infoFile))) {
                writer.write("base64_count=" + base64List.size());
                writer.newLine();
                writer.write("names_count=" + imageNames.size());
                writer.newLine();
                writer.write("timestamp=" + System.currentTimeMillis());
            }
            
            Log.d(TAG, "Saved " + base64List.size() + " base64 images and " + imageNames.size() + " names to files");
            
        } catch (IOException e) {
            Log.e(TAG, "Error saving base64 image list to files", e);
        }
    }
    
    /**
     * 从文件读取base64图片数据列表
     */
    public List<String> loadBase64ImageList() {
        // 首先尝试从JSON文件读取
        List<String> jsonResult = loadFromJson();
        if (jsonResult != null && !jsonResult.isEmpty()) {
            Log.d(TAG, "从JSON文件读取成功，数量: " + jsonResult.size());
            return jsonResult;
        }
        
        // 如果JSON读取失败，回退到文本格式
        Log.w(TAG, "JSON读取失败，回退到文本格式");
        return loadFromText();
    }
    
    /**
     * 从JSON文件读取数据
     */
    private List<String> loadFromJson() {
        try {
            File jsonFile = new File(dataDir, JSON_FILE);
            if (!jsonFile.exists()) {
                Log.d(TAG, "JSON文件不存在");
                return null;
            }
            
            Log.d(TAG, "尝试读取JSON文件: " + jsonFile.getAbsolutePath() + ", 大小: " + jsonFile.length() + " bytes");
            
            // 读取JSON文件内容
            StringBuilder content = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line);
                }
            }
            
            JSONObject data = new JSONObject(content.toString());
            JSONArray base64Array = data.getJSONArray("base64List");
            
            List<String> base64List = new ArrayList<>();
            for (int i = 0; i < base64Array.length(); i++) {
                base64List.add(base64Array.getString(i));
            }
            
            Log.d(TAG, "从JSON文件读取了 " + base64List.size() + " 个base64数据");
            return base64List;
            
        } catch (Exception e) {
            Log.e(TAG, "从JSON文件读取失败", e);
            return null;
        }
    }
    
    /**
     * 从文本文件读取数据（备用方案）
     */
    private List<String> loadFromText() {
        List<String> base64List = new ArrayList<>();
        try {
            File base64File = new File(dataDir, BASE64_FILE);
            Log.d(TAG, "尝试读取base64文件: " + base64File.getAbsolutePath() + ", 存在: " + base64File.exists());
            
            if (base64File.exists()) {
                Log.d(TAG, "base64文件大小: " + base64File.length() + " bytes");
                try (BufferedReader reader = new BufferedReader(new FileReader(base64File))) {
                    String line;
                    int lineCount = 0;
                    while ((line = reader.readLine()) != null) {
                        base64List.add(line);
                        lineCount++;
                        if (lineCount % 100 == 0) {
                            Log.d(TAG, "已读取 " + lineCount + " 行base64数据");
                        }
                    }
                    Log.d(TAG, "总共读取了 " + lineCount + " 行base64数据");
                }
            }
            Log.d(TAG, "Loaded " + base64List.size() + " base64 images from files");
        } catch (IOException e) {
            Log.e(TAG, "Error loading base64 image list from files", e);
        }
        return base64List;
    }
    
    /**
     * 从文件读取图片名称列表
     */
    public List<String> loadImageNamesList() {
        // 首先尝试从JSON文件读取
        List<String> jsonResult = loadNamesFromJson();
        if (jsonResult != null && !jsonResult.isEmpty()) {
            Log.d(TAG, "从JSON文件读取图片名称成功，数量: " + jsonResult.size());
            return jsonResult;
        }
        
        // 如果JSON读取失败，回退到文本格式
        Log.w(TAG, "JSON读取图片名称失败，回退到文本格式");
        return loadNamesFromText();
    }
    
    /**
     * 从JSON文件读取图片名称
     */
    private List<String> loadNamesFromJson() {
        try {
            File jsonFile = new File(dataDir, JSON_FILE);
            if (!jsonFile.exists()) {
                return null;
            }
            
            StringBuilder content = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line);
                }
            }
            
            JSONObject data = new JSONObject(content.toString());
            JSONArray namesArray = data.getJSONArray("imageNames");
            
            List<String> imageNames = new ArrayList<>();
            for (int i = 0; i < namesArray.length(); i++) {
                imageNames.add(namesArray.getString(i));
            }
            
            Log.d(TAG, "从JSON文件读取了 " + imageNames.size() + " 个图片名称");
            return imageNames;
            
        } catch (Exception e) {
            Log.e(TAG, "从JSON文件读取图片名称失败", e);
            return null;
        }
    }
    
    /**
     * 从文本文件读取图片名称（备用方案）
     */
    private List<String> loadNamesFromText() {
        List<String> imageNames = new ArrayList<>();
        try {
            File namesFile = new File(dataDir, NAMES_FILE);
            if (namesFile.exists()) {
                try (BufferedReader reader = new BufferedReader(new FileReader(namesFile))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        imageNames.add(line);
                    }
                }
            }
            Log.d(TAG, "Loaded " + imageNames.size() + " image names from files");
        } catch (IOException e) {
            Log.e(TAG, "Error loading image names list from files", e);
        }
        return imageNames;
    }
    
    /**
     * 清除所有数据文件
     */
    public void clearAllData() {
        try {
            // 清理JSON文件
            File jsonFile = new File(dataDir, JSON_FILE);
            if (jsonFile.exists()) {
                jsonFile.delete();
                Log.d(TAG, "删除了JSON文件");
            }
            
            // 清理文本文件
            File base64File = new File(dataDir, BASE64_FILE);
            if (base64File.exists()) {
                base64File.delete();
            }
            
            File namesFile = new File(dataDir, NAMES_FILE);
            if (namesFile.exists()) {
                namesFile.delete();
            }
            
            File infoFile = new File(dataDir, INFO_FILE);
            if (infoFile.exists()) {
                infoFile.delete();
            }
            
            Log.d(TAG, "Cleared all image data files");
            
        } catch (Exception e) {
            Log.e(TAG, "Error clearing data files", e);
        }
    }
    
    /**
     * 检查是否有数据
     */
    public boolean hasData() {
        File base64File = new File(dataDir, BASE64_FILE);
        return base64File.exists() && base64File.length() > 0;
    }
    
    /**
     * 获取数据大小信息
     */
    public String getDataSizeInfo() {
        try {
            File infoFile = new File(dataDir, INFO_FILE);
            if (infoFile.exists()) {
                try (BufferedReader reader = new BufferedReader(new FileReader(infoFile))) {
                    String line;
                    StringBuilder info = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        info.append(line).append(", ");
                    }
                    return info.toString();
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Error reading data info", e);
        }
        
        // 如果没有信息文件，返回基本统计
        File base64File = new File(dataDir, BASE64_FILE);
        File namesFile = new File(dataDir, NAMES_FILE);
        return "Base64 file: " + (base64File.exists() ? base64File.length() + " bytes" : "not found") +
               ", Names file: " + (namesFile.exists() ? namesFile.length() + " bytes" : "not found");
    }
    
    /**
     * 获取数据目录大小
     */
    public long getDataDirSize() {
        long size = 0;
        if (dataDir.exists()) {
            File[] files = dataDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    size += file.length();
                }
            }
        }
        return size;
    }
}
